<?php

namespace app\http\middleware;

use think\Request;
use think\Exception;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\SignatureInvalidException;
use UnexpectedValueException;
//令牌验证中间件
class Token
{
    public function handle(Request $request, \Closure $next)
    {
        //$host = $request->host();
        //$ip = $request->ip();
        $token= $request->header('Authorization');
        $key = config('jwt.key');
        try {
            //当前时间减去60，把时间留点余地
            JWT::$leeway = 60;
            //HS256方式，这里要和签发的时候对应
            $decoded = (array)JWT::decode($token, $key, array('HS256'));
            //请求者信息
            $request->Requester = $decoded['data'];
            return $next($request);
        }catch(SignatureInvalidException $e) {//签名不正确
            return response('签名不正确')->code(403);
        }catch(BeforeValidException $e) { //签名在某个时间点之后才能用
            return response('token失效')->code(403);
        }catch(ExpiredException $e) { //token过期
            return response('token失效')->code(403);
        }catch(UnexpectedValueException $e) {//其他错误
            return response('签名验证失败:'.$e->getMessage())->code(500);
        }catch(Exception $e) {//系统错误
            return response('签名验证失败:'.$e->getMessage())->code(500);
        }
    }
    public function signToken(Request $request){
        $confjwt =  config('jwt');
        $host = $request->host();
        $options = array(
            //签发者 可以为空
            "iss"=>$host,
            //面象的用户，可以为空
            "aud"=>$host,
            "iat"=>$confjwt['iat'],
            "nbf"=>$confjwt['nbf'],
            "exp"=> $confjwt['exp'],
            //记录的data的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
            "data"=>[
                "series_id"=>0,
                "user_id"=>0
            ]
        );
        $token = JWT::encode($options, $confjwt['key']);
        return $token;
    }
}
